<template>
  <div class="app-container">
    <el-form :inline="true" :model="homeActivity" :rules="ActivityRule" ref="activityForm" class="filter-container">
      <div class="m-bottom">首页展示活动配置</div>
      <span v-for="(info,index) in homeActivity.items" :key="index">
        <el-form-item :label="`栏位${index + 1}：`">
        <el-select v-model="info.id">
          <el-option v-for="(item,index) in processActivity.list"
                     :key="index"
                     :label="item.name"
                     :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item :label="`文案${index + 1}：`" :prop="`items.${index}.summary`" :rules="{
                 required: true, message: '文案不能为空', trigger: 'blur'
                 }">
        <el-input
          type="textarea"
          autosize
          placeholder="请输入内容"
          v-model="info.summary">
        </el-input>
      </el-form-item>
      </span>
      <el-button type="primary" @click="toSaveHomeGame('activityForm')">保存</el-button>
    </el-form>
    <hr>
    <el-form :inline="true" :model="filters" ref="refForm" class="demo-form-inline filter-container">
      <!--<el-form-item prop="dateType" label="活动时间">-->
      <!--<el-date-picker-->
      <!--v-model="filters.date"-->
      <!--class="filter-item"-->
      <!--type="datetimerange"-->
      <!--range-separator="至"-->
      <!--start-placeholder="开始日期"-->
      <!--end-placeholder="结束日期"-->
      <!--value-format="yyyy-MM-dd HH:mm:ss"-->
      <!--align="right">-->
      <!--</el-date-picker>-->
      <!--</el-form-item>-->
      <el-form-item label="活动名称：" prop="name">
        <el-input v-model="filters.name"></el-input>
      </el-form-item>
      <el-form-item label="操作人：" prop="operator">
        <el-select v-model="filters.operator">
          <el-option
            :label="'全部'"
            :value="undefined"
          ></el-option>
          <el-option v-for="item in operatorList"
                     :key="item"
                     :label="item"
                     :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="显示端：" prop="showClient">
        <el-select v-model="filters.showClient">
          <el-option v-for="item in consts.DEVICE_TYPE_ACTIVE"
                     :key="item.value"
                     :label="item.title"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="活动类型：" prop="actType">
        <el-select v-model="filters.actType">
          <el-option v-for="item in consts.OFFER_TYPE"
                     :key="item.value"
                     :label="item.title"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="状态：" prop="status">
        <el-select v-model="filters.status">
          <el-option v-for="item in consts.OFFER_STATUS"
                     :key="item.value"
                     :label="item.title"
                     :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-button type="primary" v-waves icon="el-icon-search" @click="gridSearch">搜索</el-button>
      <el-button @click="resetFilter">重置</el-button>
    </el-form>

    <el-table :data="tableData.list" v-loading="loading" element-loading-text="给我一点时间" border fit
              highlight-current-row
              style="width: 100%">
      <el-table-column label="活动入口开关时间" align="center" width="160px">
        <template slot-scope="{row}">
          {{row.showStartTime | toTime}}
          <br>
          至
          <br>
          {{row.showEndTime | toTime}}
        </template>
      </el-table-column>
      <el-table-column label="活动正式开关时间" align="center" width="160px">
        <template slot-scope="{row}">
          {{row.startTime | toTime}}
          <br>
          至
          <br>
          {{row.endTime | toTime}}
        </template>
      </el-table-column>
      <!--<el-table-column label="平台" align="center">-->
      <!--<template slot-scope="{row}">-->
      <!--{{row.gameType | toConverter('PLATFORM_TYPE') | join}}-->
      <!--</template>-->
      <!--</el-table-column>-->
      <el-table-column label="适用平台" align="center" width="200">
        <template slot-scope="{row}">
          <span v-if="row.applicablePlatformAlias!==''">
             {{row.applicablePlatformAlias}}
          </span>
          <span v-else>
            {{toArray(row.gameType) | toConverter('GAME_ID') | join}}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="显示端" align="center" width="200">
        <template slot-scope="{row}">
          {{row.showClientArray | toConverter('DEVICE_TYPE_ACTIVE') | join}}
        </template>
      </el-table-column>
      <el-table-column label="活动名称" align="center">
        <template slot-scope="{row}">
          {{row.name}}
        </template>
      </el-table-column>
      <el-table-column label="活动类型" align="center">
        <template slot-scope="{row}">
          {{row.actType | toConverter('OFFER_TYPE')}}
        </template>
      </el-table-column>
      <el-table-column label="链接地址" width="230" align="center">
        <template slot-scope="{row}">
          <div style="text-overflow: ellipsis;overflow: hidden;white-space: nowrap;text-align: left;" v-if="row.pcUrl">
            PC: <a target="_blank" :href="row.pcUrl" style="color: blue;">{{row.pcUrl}}</a>
          </div>
          <div style="text-overflow: ellipsis;overflow: hidden;white-space: nowrap;text-align: left;" v-if="row.h5Url">
            H5: <a target="_blank" :href="row.h5Url" style="color: blue;">{{row.h5Url}}</a>
          </div>
          <div style="text-overflow: ellipsis;overflow: hidden;white-space: nowrap;text-align: left;"
               v-if="row.sportUrl">
            体育-app: <a target="_blank" :href="row.sportUrl" style="color: blue;">{{row.sportUrl}}</a>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center">
        <template slot-scope="{row}">
          {{row.lastOperator}}
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center">
        <template slot-scope="{row}">
          <el-tag>
            {{row.status | toConverter('OFFER_STATUS')}}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="{row}">
          <el-button v-if="roleCheck('edit')" type="text"
                     @click="openDialog({dialogName: 'offer-edit',
                     props: row
                     })">
            编辑
          </el-button>
          <el-button v-if="roleCheck('del')" type="text" @click="handleDelete(row)">删除</el-button>
          <el-button v-if="roleCheck('switch') && row.status === 3" type="text" @click="toggleStatus(row)">启用
          </el-button>
          <el-button v-else-if="roleCheck('switch')" type="text" @click="toggleStatus(row)">禁用</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="gridSizeChange" @current-change="gridCurrentChange"
                     :current-page="filters.page" :page-sizes="gridPageSize" :page-size="filters.size"
                     :layout="gridLayout" :total="tableData.total">
      </el-pagination>
    </div>

    <el-dialog :visible.sync="dialogVisible" :before-close="() => {dialogVisible = false}">
      <offer-edit
        style="max-height:60vh; overflow: auto"
        :id="dialogProps.id"
        :row-data="dialogProps"
        @on-success="saveEdition"
        v-if="dialogName === 'offer-edit'"/>
    </el-dialog>
  </div>
</template>

<script>
import { form, grid, dialog } from '@/build';

import {
  marketingOfferUpdateStatus as statusApi,
  marketingOperatorApi as operatorApi,
  marketingOfferDeleteApi as deleteApi,
  marketingOfferListApi as listApi,
  marketingOfferDropListApi as dropListApi,
  marketingOfferSaveHomeGameApi as saveHomeGameApi,
  marketingOfferGetHomeGameApi as getHomeGameApi,
} from '@/services/api/marketing';

import OfferEdit from './offerEdit';

export default {
  name: 'offer-list',

  mixins: [form, grid, dialog],

  components: {
    OfferEdit,
  },

  data() {
    return {
      operatorList: [],
      tableData: {
        list: [],
        total: 0,
      },
      processActivity: {
        list: [],
        total: 0,
      },
      filters: {
        page: 1,
        size: 20,
        name: undefined,
        operator: undefined,
        showClient: undefined,
        gameType: undefined,
        actType: undefined,
        status: consts.ALL,
      },
      filterDateType: false,
      homeActivity: {
        items: [
          {
            id: '',
            summary: '',
          },
          {
            id: '',
            summary: '',
          },
          {
            id: '',
            summary: '',
          },
        ],
      },
      ActivityRule: {
        summary: [{
          required: true,
          message: '文案不能为空！',
          trigger: 'blur',
        }],
      },
    };
  },
  watch: {
    // processActivity: {
    //   handler(val) {
    //     if (this.homeActivity.items[0].id === 0) {
    //       this.homeActivity.items = this.homeActivity.items.map((item, index) => {
    //         item.id = val.list[index].id;
    //         return item;
    //       });
    //     }
    //   },
    // },
    $route: {
      handler(newval) {
        const isFresh = localStorage.getItem('freshpage');
        if (isFresh) {
          this.doGet({ action: 'getGrid' });
          localStorage.removeItem('freshpage');
        }
      },
    },
  },
  methods: {
    toArray(string) {
      return eval(`(${string})`);
    },
    handleDelete({ id }) {
      this.$confirm('确定要删除此广告吗？（删除后前台则不显示此广告图）', '删除公告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.$refs.confirm.$el.onclick = function (e) {
              e = e || window.event;
              if (e.detail !== 0) {
                done();
              }
            };
          } else {
            done();
          }
        },
      })
        .then(() => {
          deleteApi({
            id,
          })
            .then(([result, data]) => {
              if (result) {
                this.doGet({ action: 'getGrid' });
                this.$message({
                  type: 'success',
                  message: '删除成功!',
                });
              } else {
                this.$message({
                  type: 'error',
                  message: `删除失败!${data.message}`,
                });
              }
            });
        })
        .catch(() => {
        });
    },

    toggleStatus({ id, status }) {
      const action = status !== 3 ? '禁用' : '启用';
      this.$confirm(`确定要${action}此优惠活动吗？`, `${action}优惠活动`, {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          statusApi({
            id,
            status: status !== 3 ? 1 : 0,
          })
            .then(([result, data]) => {
              if (result) {
                this.doGet({ action: 'getGrid' });
                this.$message({
                  type: 'success',
                  message: `${action}成功!`,
                });
              } else {
                this.$message({
                  type: 'error',
                  message: `${action}失败!${data.message}`,
                });
              }
            });
        })
        .catch(() => {
        });
    },

    resetFilter() {
      this.resetForm('refForm');
      this.gridSearch();
    },
    toSaveHomeGame(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.doSave({ action: 'saveHomeActivity' });
        } else {
          return false;
        }
      });
    },
    saveEdition() {
      this.dialogVisible = false;
      this.doGet({ action: 'getGrid' });
      this.doSave({ action: 'saveHomeActivity' });
    },
  },

  mounted() {
    this.bindGet(operatorApi, 'operatorList', {});

    this.bindGet(listApi, 'tableData', {
      action: 'getGrid',
      sendingData: 'filters',
    });
    this.bindGet(dropListApi, 'processActivity', {
      action: 'getProcessActivity',
      beforeSend: data =>
      // data.status = consts.ALL;
      // return data;
        ({}),
      sendingData: 'filters',
      format: (data) => {
        data = _.filter(data, item => item.status < 2);
        return { list: data };
      },
    });
    this.bindGet(getHomeGameApi, 'homeActivity', {
      action: 'getHomeActivity',
      format: (data) => {
        if (data) {
          data.forEach((item, index) => {
            this.homeActivity.items[index].id = item.id;
            this.homeActivity.items[index].summary = item.summary;
          });
          data = { items: this.homeActivity.items };
        } else {
          /* else if (!_.isEmpty(this.processActivity.list)) {
            data = this.homeActivity.items.map((item, index) => {
              item.id = this.processActivity.list[index].id;
              item.summary = this.processActivity.list[index].summary;
              return item;
            });
          } */
          data = this.homeActivity;
        }
        return data;
      },
    });
    this.bindSave(saveHomeGameApi, 'saveHomeActivity', 'homeActivity', {
      afterSuccess: () => {
        this.doGet({ action: 'getHomeActivity' });
      },
    });
    this.getAll();
  },
};
</script>
<style scoped>
  .m-bottom {
    margin-bottom: 10px;
  }
</style>
